package com.fly.autogetcode;

/**
 * Created by weifeiyang on 2016/7/29 0029.
 */

import android.app.Activity;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.EditText;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 读取短信验证码，并设置验证码
 * Created by cool on 2016/1/4.
 */
public class ReadSmsContent extends ContentObserver {
    private Cursor cursor = null;
    private Activity mActivity;
    private EditText mEditText;
    private SharedPreferences sharedPreferences;

    public ReadSmsContent(Handler handler, Activity activity, EditText editText) {
        super(handler);
        this.mActivity = activity;
        this.mEditText = editText;
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {
        // 第一次回调 不是我们想要的 直接返回
        if (uri.toString().equals("content://sms/raw")) {
            return;
        }

        /*
            读取收件箱中的短信

            address 发件人手机号码:
            body 信息内容:
            read 是否查看:
            date 发送时间:
         */
        cursor = mActivity.getContentResolver().query(Uri.parse("content://sms/inbox"),
                new String[]{"_id", "address", "body", "read"}, null, null, "_id desc");//按降序排列

//        指定号码
//        mActivity.managedQuery(Uri.parse("content://sms/inbox"),
//                new String[]{"_id", "address", "body", "read"}, "address=? and read=?", new String[]{"10086", "0"}, "_id desc");

        if (null != cursor && cursor.getCount() > 0) {
            cursor.moveToNext();//指向首位
            int smsbodyColumn = cursor.getColumnIndex("body");//body位置
            String smsBody = cursor.getString(smsbodyColumn);//获取内容
            String verifyCode = getDynamicPassword(smsBody);
            if (TextUtils.isEmpty(verifyCode)) {
                return;
            }
            if (mEditText == null) {
                throw new RuntimeException("你传的EditText为空");
            }
            mEditText.setText(verifyCode);
            //EditText获取焦点，3个属性必须同时设置
            mEditText.setFocusable(true);
            mEditText.setFocusableInTouchMode(true);
            mEditText.requestFocus();
            mEditText.setSelection(verifyCode.length());//设置光标位置
        }

        if (null != cursor && !cursor.isClosed()) {
            cursor.close();
        }
    }

    /**
     * 从字符串中截取连续4位数字
     * 用于从短信中获取动态密码
     *
     * @param str 短信内容
     * @return 截取得到的4位动态密码
     */
    public static String getDynamicPassword(String str) {
        Pattern continuousNumberPattern = Pattern.compile("[0-9\\.]+");
        Matcher m = continuousNumberPattern.matcher(str);
        String dynamicPassword = "";
        while (m.find()) {
            if (m.group().length() == 4) {
                dynamicPassword = m.group();
            }
        }

        return dynamicPassword;
    }
}
